package com.orange.cetback.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.orange.cetback.common.enums.MaterialType;
import com.orange.cetback.common.properties.YoudaoProperties;
import com.orange.cetback.common.utils.AuthV3Util;
import com.orange.cetback.common.utils.HttpUtil;
import com.orange.cetback.common.vo.PageResult;
import com.orange.cetback.pojo.dto.MaterialDTO;
import com.orange.cetback.pojo.dto.WritingDTO;
import com.orange.cetback.pojo.entity.Materials;
import com.orange.cetback.mapper.MaterialsMapper;
import com.orange.cetback.pojo.entity.QuestionOptions;
import com.orange.cetback.pojo.entity.Questions;
import com.orange.cetback.pojo.vo.*;
import com.orange.cetback.service.ExamPapersService;
import com.orange.cetback.service.MaterialsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.orange.cetback.service.QuestionOptionsService;
import com.orange.cetback.service.QuestionsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenenjun
 * @since 2025-02-16
 */
@Service
public class MaterialsServiceImpl extends ServiceImpl<MaterialsMapper, Materials> implements MaterialsService {

    @Autowired
    private ExamPapersService examPapersService;
    @Autowired
    private QuestionsService questionsService;
    @Autowired
    private QuestionOptionsService questionOptionsService;
    /**
     * 根据试卷ID获取关联的词汇材料列表及其对应题目
     *
     * @param paperId 试卷唯一标识符，用于查询关联的教材材料
     * @return List<VocabularyVO> 词汇材料视图对象列表，每个对象包含：
     *         1. 基础材料属性
     *         2. 关联的题目列表（通过questions字段返回）
     */
    @Override
    public List<VocabularyVO> MaterialList(Integer paperId) {
        // 构建材料查询条件：筛选指定paperId的材料记录
        LambdaQueryWrapper<Materials> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Materials::getPaperId, paperId);

        List<Materials> materials = this.baseMapper.selectList(wrapper);

        // 转换材料实体为视图对象，并补充关联题目数据
        List<VocabularyVO> vocabularyVOList = new ArrayList<>();
        for (Materials material: materials) {
            VocabularyVO vo = new VocabularyVO();
            // 复制基础属性到视图对象
            BeanUtils.copyProperties(material, vo);

            // 获取当前材料关联的题目列表
            List<Questions> questions = questionsService.getQuestionsByMaterialId(material.getMaterialId());
            vo.setQuestions(questions);

            vocabularyVOList.add(vo);
        }
        return vocabularyVOList;
    }

    @Override
    public VocabularyVO vocabulary(Integer paperId) {
        // 构建材料查询条件：筛选指定paperId的材料记录
        LambdaQueryWrapper<Materials> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Materials::getPaperId, paperId);
        wrapper.eq(Materials::getMaterialType, MaterialType.VOCABULARY);

        Materials material = this.baseMapper.selectOne(wrapper);
        // 转换材料实体为视图对象，并补充关联题目数据
        VocabularyVO vo = new VocabularyVO();
        // 复制基础属性到视图对象
        BeanUtils.copyProperties(material, vo);

        // 获取当前材料关联的题目列表
        List<Questions> questions = questionsService.getQuestionsByMaterialId(material.getMaterialId());
        vo.setQuestions(questions);

        List<QuestionOptions> options = questionOptionsService.OptionsByMaterialId(material.getMaterialId());
        vo.setOptions(options);

        return vo;
    }

    @Override
    public LongReadingVO longReading(Integer paperId) {
        // 构建材料查询条件：筛选指定paperId的材料记录
        LambdaQueryWrapper<Materials> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Materials::getPaperId, paperId);
        wrapper.eq(Materials::getMaterialType, MaterialType.LONG_READING);

        Materials material = this.baseMapper.selectOne(wrapper);
        // 转换材料实体为视图对象，并补充关联题目数据
        LongReadingVO vo = new LongReadingVO();
        // 复制基础属性到视图对象
        BeanUtils.copyProperties(material, vo);

        // 获取当前材料关联的题目列表
        List<Questions> questions = questionsService.getQuestionsByMaterialId(material.getMaterialId());
        vo.setQuestions(questions);

        List<QuestionOptions> options = questionOptionsService.OptionsByMaterialId(material.getMaterialId());
        vo.setOptions(options);

        return vo;
    }

    @Override
    public List<CarefulReadingVO> carefulReading(Integer paperId) {
        // 构建材料查询条件：筛选指定paperId的材料记录
        LambdaQueryWrapper<Materials> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Materials::getPaperId, paperId);
        wrapper.eq(Materials::getMaterialType, MaterialType.CAREFUL_READING);

        List<Materials> materials = this.baseMapper.selectList(wrapper);

        // 转换材料实体为视图对象，并补充关联题目数据
        List<CarefulReadingVO> carefulReadingVOS = new ArrayList<>();
        for (Materials material: materials) {
            CarefulReadingVO vo = new CarefulReadingVO();
            // 复制基础属性到视图对象
            BeanUtils.copyProperties(material, vo);

            // 获取当前材料关联的题目列表
            List<Questions> questions = questionsService.getQuestionsOptionsByMaterialId(material.getMaterialId());
            vo.setQuestions(questions);

            carefulReadingVOS.add(vo);
        }
        return carefulReadingVOS;
    }

    @Override
    public WritingVO writing(Integer paperId) {
        // 构建材料查询条件：筛选指定paperId的材料记录
        LambdaQueryWrapper<Materials> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Materials::getPaperId, paperId);
        wrapper.eq(Materials::getMaterialType, MaterialType.WRITING);

        Materials material = this.baseMapper.selectOne(wrapper);

        WritingVO vo = new WritingVO();
        BeanUtils.copyProperties(material, vo);
        Questions questions = questionsService.getQuestionsByMaterialId(material.getMaterialId()).get(0);
        vo.setQuestions(questions);
        return vo;
    }

    @Override
    public TranslationVO translation(Integer paperId) {
        // 构建材料查询条件：筛选指定paperId的材料记录
        LambdaQueryWrapper<Materials> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Materials::getPaperId, paperId);
        wrapper.eq(Materials::getMaterialType, MaterialType.TRANSLATION);
        Materials material = this.baseMapper.selectOne(wrapper);
        TranslationVO vo = new TranslationVO();
        BeanUtils.copyProperties(material, vo);
        Questions questions = questionsService.getQuestionsByMaterialId(material.getMaterialId()).get(0);
        vo.setQuestions(questions);
        return vo;
    }

    @Override
    public PageResult<MaterialVO> pageQuery(MaterialDTO materialDTO) {
        Page<Materials> page = new Page<>(materialDTO.getPageNum(), materialDTO.getPageSize());
        LambdaQueryWrapper<Materials> wrapper = new LambdaQueryWrapper<>();
        if (materialDTO.getMaterialType() != null && !materialDTO.getMaterialType().equals("")){
            wrapper.eq(Materials::getMaterialType, materialDTO.getMaterialType());
        }
        wrapper.like(Materials::getContent, materialDTO.getContent());
        this.baseMapper.selectPage(page, wrapper);
        List<MaterialVO> materialVOList = page.getRecords().stream().map(material -> {
            MaterialVO materialVO = new MaterialVO();
            BeanUtils.copyProperties(material, materialVO);
            materialVO.setPaperTitle(examPapersService.getById(material.getPaperId()).getPaperTitle());
            return materialVO;
        }).collect(Collectors.toList());
        PageResult<MaterialVO> pageResult = new PageResult<>(page.getTotal(), materialVOList);
        return pageResult;
    }

}
